﻿using System;
using System.Collections.Generic;
using System.Linq;
using Core.Combat.FlyerObj.Data;
using UnityEngine;

namespace Core.Combat
{
    public class CombatController : MonoBehaviour
    {
        public BulletDataModel defaultBulletData;
        
        public BulletGenerator BulletGenerator { get; protected set; }

        private void Awake()
        {
            BulletGenerator = GetComponent<BulletGenerator>();
        }

        private void Start()
        {
            InitBulletGen();
        }

        public void InitBulletGen()
        {
            BulletGenerator.InitData(defaultBulletData);
        }
    }

    /// <summary>
    /// 战斗系统辅助工具
    /// </summary>
    public static class CombatHelper
    {
        private static readonly Collider2D[] _results = new Collider2D[10];
        public static Collider2D TryGetNearestTarget(this Transform originPoint, float range, LayerMask targetLayer, LayerMask blockLayer)
        {
            int result = Physics2D.OverlapCircleNonAlloc(originPoint.position, range, _results, targetLayer);
            if (result > 0)
            {
                Collider2D target = null;
                float minDist = float.MaxValue;
                foreach (var res in _results)
                {
                    if (res == null)
                        continue;
                    float dist = Vector2.Distance(originPoint.position, res.transform.position);
                    if (minDist > dist && !HadBlockBetweenTheTwo(originPoint.transform, res.transform, blockLayer))
                    {
                        minDist = dist;
                        target = res;
                    }
                }

                return target;
            }

            return null;
        }

        public static bool HadBlockBetweenTheTwo(Transform a, Transform b, LayerMask blockLayer)
        {
            return Physics2D.Linecast(a.position, b.position, blockLayer);
        }

        public static bool IsInTags(this IEnumerable<string> tags, string tag)
        {
            return tags.Any(t => t == tag);
        }

        public static bool IsInLayer(this LayerMask layer, LayerMask targetLayer)
        {
            return (layer & (1 << targetLayer)) != 0;
        }
    }
}